package mn.idax.exchange.otc.task;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.elasticjob.lite.annotation.ElasticSimpleJob;
import lombok.SneakyThrows;
import mn.idax.exchange.otc.constant.CommonConstant;
import mn.idax.exchange.otc.domain.capital.CapitalAPIParamsDTO;
import mn.idax.exchange.otc.entity.OTCOrder;
import mn.idax.exchange.otc.enums.response.OrderResponseEnum;
import mn.idax.exchange.otc.exception.IdaxException;
import mn.idax.exchange.otc.service.AccountService;
import mn.idax.exchange.otc.service.OTCOrderService;
import mn.idax.exchange.otc.service.impl.MemoryService;
import mn.idax.exchange.otc.util.DateUtils;
import mn.idax.exchange.otc.util.LogUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * @Auther: dison
 * @Date: 2018/9/28 14:04
 * @Description:
 */
@ElasticSimpleJob(cron = "0/5 * * * * ?")
@Component
public class OrderUnforzenJob implements SimpleJob {


    @Autowired
    private AccountService accountService;

    @Autowired
    private OTCOrderService otcOrderService;

    @SneakyThrows
    @Override
    public void execute(ShardingContext shardingContext) {

        //撤单开关
        if (Objects.isNull(MemoryService.SYSTEMSETTINGMAP.get(CommonConstant.OTC_CANCELORDER_SWITCH)) ||
                !Boolean.valueOf(MemoryService.SYSTEMSETTINGMAP.get(CommonConstant.OTC_CANCELORDER_SWITCH).toString())){
           return;
        }

        //获取所有订单状态为1，下单时间超过15min的订单
        List<OTCOrder> otcOrders = otcOrderService.getOrderPayTimeout(DateUtils.getUTCNow());

        for (OTCOrder otcOrder : otcOrders) {

            CapitalAPIParamsDTO capitalAPIParamsDTO = otcOrderService.checkForzenOrderServiceParams(otcOrder, otcOrder.getBuyer());

            //如果插入失敗 || 非第一次插入
            if (!capitalAPIParamsDTO.getInsert()) {
                throw new IdaxException(OrderResponseEnum.ORDERE_UNFROZEN_INSERT_FAIL.getRespCode());
            }

        }
        LogUtils.info(this.getClass(),"OrderUnforzenJob run finish ,deal order total " +otcOrders.size());

    }
}
